package cn.com.chengmandian.core.web.utils;

import cn.com.chengmandian.core.common.constants.CommonConstant;
import cn.com.chengmandian.core.common.enums.ClientsEnum;
import cn.com.chengmandian.core.web.constants.TokenAttrEnum;
import cn.com.chengmandian.core.web.pojo.LoginUser;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

@Slf4j
public class AuthUtil {
    public static void main(String[] args) throws  Exception {
        System.out.println(getLoginUser("eyJhbGciOiJIUzI1NiIsIlR5cGUiOiJKd3QiLCJ0eXAiOiJKV1QifQ.eyJhdWQiOiIyIiwibmlja25hbWUiOiLnrqHnkIblkZjmtYvor5UifQ.FQSDcD12UvOgBDykJ8A61QKq-Q1vff3hXsyOOBKPOOM",
                ClientsEnum.MALL_ADMIN_WEB));
    }

    /**
     * 获取用户信息
     * @param token
     * @param client
     * @return
     */
    public static LoginUser getLoginUser(String token, ClientsEnum client) {
        if (!JWTUtil.verify(token, client.getSecret().getBytes())) {
            if (SpringContextUtil.isDev()) {
                log.error("Token验证未通过：{}", token);
            }
            return null;
        }
        JWT jwt = JWTUtil.parseToken(token);
        LoginUser loginUser = null;
        // 原有系统集成
        if (client == ClientsEnum.MALL_MEMBER_MINI || client == ClientsEnum.MALL_OPS_MINI || client == ClientsEnum.MALL_ADMIN_WEB) {
            JSONObject payloads = jwt.getPayloads();
            loginUser = new LoginUser();
            loginUser.setId(Integer.parseInt(payloads.getStr("aud")));
            loginUser.setName(payloads.getStr("nickname"));
            loginUser.setExpireDate(DateUtil.offsetDay(new Date(), 30).getTime());
        } else {
            loginUser = jwt.getPayloads().toBean(LoginUser.class);
        }
        if (loginUser == null) return null;
        if (SpringContextUtil.isDev()) {
            log.info("Token：{}", JSONUtil.toJsonStr(loginUser));
        }

        if (loginUser.getExpireDate() < DateUtil.date().getTime()) {
            log.info("Token已过期：{}", token);
            return null;
        }
        return loginUser;
    }

    public static LoginUser getLoginUser(HttpServletRequest request, ClientsEnum client) {
        String token = request.getHeader(client.getHeaderName());
        if (StrUtil.isBlank(token)) return null;
        return getLoginUser(request.getHeader(client.getHeaderName()), client);
    }

    /**
     * 获取当前登陆用户
     * @return
     */
    public static LoginUser getLoginUser() {
        HttpServletRequest request = ServletUtil.getRequest();
        if (request == null) return null;
        String clientId = request.getHeader(CommonConstant.HEADER_CLIENT_ID);
        if (StrUtil.isBlank(clientId)) return null;
        ClientsEnum client = ClientsEnum.codeOf(clientId);
        if (client == null) return null;
        return getLoginUser(request, client);
    }

    private static <T> T get(String key) {
        LoginUser user = getLoginUser();
        if (user.getAttrs() == null || !user.getAttrs().containsKey(key)) return null;
        return (T)user.getAttrs().get(key);
    }

    /**
     * 获取合作商ID
     * @return
     */
    public static Integer getMerchantId() {
        return get(TokenAttrEnum.MID.getCode());
    }

    /**
     * 获取门店列表
     * @return
     */
    public static List<Integer> getShops() {
        List<Integer> res = get(TokenAttrEnum.SPS.getCode());
        return res == null ? new ArrayList<>() : res;
    }

    /**
     * 获取仓库列表
     * @return
     */
    public static List<Integer> getWarehouses() {
        List<Integer> res = get(TokenAttrEnum.WHS.getCode());
        return res == null ? new ArrayList<>() : res;
    }
}
